/**
 * Created by chenyong on 2015/1/26.
 */
var express = require('express');
var request = require('request');
var router = express.Router();
var config = require('./../config');
var async = require("async");
var fs = require('fs'),
    path = require('path');

//更新为redis数据缓存方式
var CachemanRedis = require('cacheman-redis');
var cache = new CachemanRedis(config.cachestore);

router.get('/',function(req,res) {
    res.redirect('/#work');
});

//评论
router.get('/:id/comment', function(req, res, next){
    var access_token=config.api.token();
    var ua = req.useragent;
    var req_panoinfo = {
        url: config.api.rootpath + '/api/panos/' + req.params.id,
        json:true,
        headers: {'Authorization': 'Bearer ' + access_token}
    };
    request.get(req_panoinfo, function (error, response, data){
        if (!error && response.statusCode === 200)
        {
            var info = {
                panoid : data.panoid,
                title : data.title,
                url:  'http://' + req.host + '/panos/'+ data.panoid
            }
            res.render('comment', info);
        }
        else{
            next();
        }
    });
});

/* 2015-12-21 created by wangkui
  * 根据panoid读取redis数据库中的数据,如果数据不存在或已过期，
  * 则到mongodb中读取数据，并做以下判断处理
 1.是否远程
 2.大图xml配置文件是否存在
 3.模版文件是否存在
 4.生成cache 中的key 和 value 值
 5.保存数据到redis中
 */
router.get('/:id',function(req,res,next){
    var access_token=config.api.token();
    var ua = req.useragent;
    var req_panoinfo = {
        url: config.api.rootpath + '/api/panos/' + req.params.id,
        json:true,
        headers: {'Authorization': 'Bearer ' + access_token}
    };
    var key='';      //cache key值
    var tourxml='';  //tour.xml 值
    var template=''; //template
    if (ua.isMobile || ua.isiPad){
        //移动设备
        key='M_';
    }else{
        //pc设备
        key='P_';
    }
    key=key+req.params.id;
    //读取redis中的数据
    cache.get(key,function(err,value){
        if(err|| value==undefined||value=='') {
            request.get(req_panoinfo, function (error, response, data){
                if (!error && response.statusCode === 200){
                    //如果cache中数据过期或数据为空则保存到cache中
                    async.series({
                        //判断模版文件
                        first:function(callback){
                            if(data.template==''||data.template==undefined){
                                callback();
                            }else{
                                //获取template
                                gettemplate(ua,data.template,function(result){
                                    template=result;
                                    callback();
                                })
                            }
                        },
                        second:function(callback){
                            if(data.tourxmlpath==undefined||data.tourxmlpath==''){
                                callback();
                            }else{
                                //获取tourxml文件
                                getTourxml(ua,'http://'+req.headers.host,data.tourxmlpath,function(result){
                                    tourxml=result;
                                    callback();
                                });
                            }
                        }
                    },function(err,results){
                        if(tourxml!=''&&template!=''){
                            data.tourxmlpath=tourxml;
                            data.template=template;
                            cache.set(key,data,24*60*1000,function(err){
                                if(err){console.log(err);}
                            });
                            res.render(template, data);
                        }
                        else{
                            next();
                        }
                    });
                }
                else{
                    next();
                }
            });
        }else{
            template=value.template;
            res.render(template, value);
        }
    });
});
//获取tourxml
var getTourxml=function(ua,url,tourxmlpath,callback){
    var tourxml;
    if (tourxmlpath.indexOf('http:') > -1) {
        //绝对地址
        request.head(tourxmlpath, function (error, response) {
            if (!error && response.statusCode == 200 && response.headers["content-length"] != 0) {
                tourxml = tourxmlpath;
                callback(tourxml);
            }
            else{
                //远端文件不存在
                callback('');
            }
        });
    }
    else {
        if (ua.isMobile || ua.isiPad) {
            request.head(url+tourxmlpath.replace(".xml", "-mobile.xml"), function (error, response) {
                if (!error && response.statusCode == 200 && response.headers["content-length"] != 0) {
                    tourxml = tourxmlpath.replace(".xml", "-mobile.xml");
                    callback(tourxml);
                }
                else {
                    request.head(url+tourxmlpath, function (error, response) {
                        if (!error && response.statusCode == 200 && response.headers["content-length"] != 0) {
                            tourxml = tourxmlpath;
                            callback(tourxml);
                        }
                        else {
                            callback('');
                        }
                    });
                }
            });
        }
        else {
            request.head(url+tourxmlpath.replace(".xml", "-desktop.xml"), function (error, response) {
                if (!error && response.statusCode == 200 && response.headers["content-length"] != 0) {
                    tourxml = tourxmlpath.replace(".xml", "-desktop.xml");
                    callback(tourxml);
                }
                else {
                    request.head(url+tourxmlpath, function (error, response) {
                        if (!error && response.statusCode == 200 && response.headers["content-length"] != 0) {
                            tourxml = tourxmlpath;
                            callback(tourxml);
                        }
                        else {
                            callback('');
                        }
                    });
                }
            });
        }
    }
};
//获取template文件
var gettemplate=function(ua,template_Relative,callback){
    var template;
    var newtemplate_Relative='';
    if (ua.isMobile || ua.isiPad) {
        //移动设备
        newtemplate_Relative = template_Relative + '-mobile.html';
    } else {
        //桌面
        newtemplate_Relative = template_Relative + '-desktop.html';
    }
    var filenamepath = '/views/panotpl/' + newtemplate_Relative;
    var tourxmlpath = path.normalize(__dirname + '/..') + filenamepath;
    fs.exists(tourxmlpath, function (exists) {
        if (exists == false) {
            filenamepath = '/views/panotpl/' + template_Relative + ".html";
            tourxmlpath = path.normalize(__dirname + '/..') + filenamepath;
            fs.exists(tourxmlpath, function (exists) {
                if (exists == false) {
                    //无模版文件，抛出
                    callback('');
                } else {
                    template = 'panotpl/'+template_Relative;
                    callback(template);
                }
            });
        }
        else {
            template = "panotpl/"+newtemplate_Relative.replace('.html','');
            callback(template);
        }
    });
};


module.exports = router;